package com.lskj.shiro.util;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.netty.util.CharsetUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author zzq
 * @Date 2020/4/1 0:32
 * @Version 1.0
 */
@Component
public class FastdfsUtil {

    @Resource
    private FastFileStorageClient fastFileStorageClient;

    public StorePath upload(MultipartFile file) throws IOException {
        Set<MetaData> mataData = new HashSet<>();
        mataData.add(new MetaData("author", "zzq"));
        mataData.add(new MetaData("description",file.getOriginalFilename()));
        StorePath storePath = fastFileStorageClient.uploadFile(
                file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()),
                mataData);
        return storePath;
    }

    public StorePath upload(String path) throws IOException{
        File file = new File(path);
        Set<MetaData> mataData = new HashSet<>();
        mataData.add(new MetaData("author", "zzq"));
        mataData.add(new MetaData("description",file.getName()));
        StorePath storePath = fastFileStorageClient.uploadFile(
                new FileInputStream(file), file.length(),
                path.substring(path.lastIndexOf(46)+1),
                mataData);
        return storePath;
    }

    public void delete(String path) {
        fastFileStorageClient.deleteFile(path);
    }

    public void delete(String group,String path) {
        fastFileStorageClient.deleteFile(group,path);
    }

    public void download(String path, String filename, HttpServletResponse response) throws IOException {
        StorePath storePath = StorePath.parseFromUrl(path);
        if (StringUtils.isBlank(filename)) {
            filename = FilenameUtils.getName(storePath.getPath());
        }
        byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, CharsetUtil.UTF_8));
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }

}
